<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchConditionNum="4" :searchFunc="searchFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.agentNo" :placeholder="'代理商号'" />
        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchNo']" placeholder="商户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />

        <jeepay-text-up v-model:value="vdata.searchData['qrcId']" placeholder="码牌ID" />
        
        <jeepay-text-up v-model:value="vdata.searchData['appId']" placeholder="应用AppId" />
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="false"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        :tableExportFunc="$access('ENT_DEVICE_QRC_EXPORT') ? tableExportFunc : null"
        :rowSelection="{ type: 'checkbox', onChange: infoTableSelectChangeFunc }"
        rowKey="qrcId"
      >
        <template #topBtnSlot>
          <a-button type="primary" @click="addOrEditFunc()"><PlusOutlined /> 申请新码</a-button>

          <!-- <a-button @click="batchChecked(true)">全选</a-button>
          <a-button @click="batchChecked(false)">反选</a-button> -->
          <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT')" type="primary" @click="allotBatchFunc"><partition-outlined />勾选划拨/收回</a-button>
          <!-- <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT')" type="primary" @click="allotByBatchIdFunc">批次划拨</a-button> -->
          <a-button v-if="$access('ENT_DEVICE_QRC_EXPORT')" @click="tableExportByBatchSelectFunc">导出选择项</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'qrcId'">
            {{ record.qrcId }}
            <QrcodeOutlined style="font-size: 16px" @click="showQrImgFunc(record.qrcId)" />
          </template>

          <template v-if="column.key === 'mchNo'">
            <template v-if="record.bindState == 0"><exclamation-circle-outlined />未绑定</template>
            <template v-else>已绑定商户: {{ record.mchNo }}({{ record.mchName }})<br>应用： {{ record.appId }}<br>门店： {{ record.storeId }}</template>
          </template>

          <template v-if="column.key === 'agentNo'">
            {{ record.agentName }}<br>{{ record.agentNo }}
          </template>

          <template v-if="column.key === 'qrcState'">
            <JeepayTableColState :state="record.qrcState" :showSwitchType="$access('ENT_DEVICE_QRC_EDIT')" :onChange="(state) => { return updateState(record.qrcId, state)}" />
          </template>

          <template v-if="column.key === 'fixedFlag'">
            <span v-if="record.fixedFlag === 0">任意金额</span>
            <span v-else>{{ record.fixedPayAmount/100 }}</span>
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_DEVICE_QRC_VIEW')" type="link" @click="showQrImgFunc(record.qrcId)">详情</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT') && record.isSelf" type="link" @click="showBind(record.qrcId)">绑定</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_RELIEVE') && record.bindState == 1 && record.isSelf" type="link" @click="unBindFunc(record.qrcId)">解绑</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_ALLOT')" type="link" @click="allotFunc(record)">划拨/收回</a-button>
              <a-button v-if="$access('ENT_DEVICE_QRC_EDIT') && record.bindState == 1" type="link" @click="getBindDeviceFunc(record.qrcId)">受支持设备</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

      <!-- <AddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" /> -->

      <Bind ref="bindRef" :callbackFunc="searchFunc" />

      <JeepayQrcDeviceList ref="jeepayQrcDeviceListRef" sysType="AGENT" />

      <JeepayModelAgentList ref="jeepayModelAgentList" showType="AGENT" @selectFinishFunc="searchAgentFinishFunc" />
      
      <!-- 批次号划拨弹窗 -->
      <a-modal v-model:visible="vdata.allotByBatchIdVisible" title="按批次号划拨" @ok="allotOk">
        <a-form ref="allotFormModel" :model="vdata.allotObject" layout="vertical" :rules="vdata.allotRules">
          <a-form-item label="批次号：" name="batchId">
            <a-input v-model:value="vdata.allotObject.batchId" placeholder="请输入批次号" />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal v-model:visible="vdata.exportVisible" title="导出选项" :width="500" @ok="tableExportDowonloadFunc">
        <a-radio-group v-model:value="vdata.exportModel">
          <a-radio value="infoAndUrl" style="margin-bottom: 10px;">Excel： 二维码信息并且包含二维码解析URL</a-radio><br>
          <a-radio value="templateImg" style="margin-bottom: 10px;">压缩包： 模板图片（如果有）</a-radio> <br>
          <a-radio value="qrcode" style="margin-bottom: 10px;">压缩包： 二维码图片(不含编号)</a-radio><br>
          <a-radio value="qrcodeAndQrcId" style="margin-bottom: 10px;">压缩包： 二维码图片(含编号) </a-radio><br>
        </a-radio-group>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import Bind from './Bind.vue'
import {API_URL_MCH_QR_CODE_LIST, req, reqLoad, $qrcShellViewByQrc, $exportExcel, exportExcelUrl, $unbindQrc, $allotQrc } from '@/api/manage'
import { ref, reactive, provide, getCurrentInstance, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import fileDownload from 'js-file-download'
import {getCurrentDatetime} from '@/utils/util'

// 导入全局函数
const { $infoBox, $access, $viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

// infoTable组件
const infoTable = ref()

const bindRef = ref()

const jeepayQrcDeviceListRef = ref()

const allotFormModel = ref()

const jeepayModelAgentList = ref()

const dateRangePicker = ref()

// eslint-disable-next-line no-unused-vars
const tableColumns = ref([
  { key: 'qrcId', title: '二维码', },
  { key: 'agentNo', title: '代理商', dataIndex: 'agentNo', agentEntCol: true },
  { key: 'mchNo', title: '绑定商户信息' },
  { key: 'entryPage',  title: '扫码页面', customRender: ({ record }) => {return record.entryPage == 'default' ? '默认' : record.entryPage == 'h5' ? 'H5' : '小程序'} , },
  { key: 'qrcState', title: '状态', },
  { key: 'fixedFlag', title: '固定金额', },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期', },
  { key: 'op', title: '操作', fixed: 'right', align: 'center',}
])


const vdata : any = reactive({
  searchData: {},
  exportVisible: false, // 显示导出弹层
  exportModel: '', //二维码导出模式

  listRecords: [], //当前列表页的缓存数据

  listExportIds: null, //列表的批量导出选择项目

  allotByBatchIdVisible: false, // 批次划拨设备弹窗
  allotObject: {
    agentNo: null, // 划拨代理商号
    allotType: null, // 划拨类型：select-勾选划拨  batch-批次划拨
    batchId: null, // 批次号，划拨类型为 batch-批次划拨 时必填
    allotIds: [] as any, // 要划拨的码ID，划拨类型为 select-勾选划拨 时必填
  } as any, // 划拨设备对象
  allotRules: {
    batchId: [{ required: true, message: '请输入批次号', trigger: 'blur' }]
  }
})


onMounted(() => {
  vdata.searchData['mchNo'] = useRoute().query.mchNo
  searchFunc()
})


// 向所有子组件注入刷新事件
provide('listPageSearchFunc', searchFunc)

function searchFunc () {
  infoTable.value.refTable(true)
}
// 请求table接口数据
function reqTableDataFunc (params) {
  return req.list(API_URL_MCH_QR_CODE_LIST, params).then((res) => {
    vdata.listRecords = (res && res.records) || []
    return Promise.resolve(res)
  })
}


// 新增 or 修改函数
function addOrEditFunc(){
  $infoBox.message.success('请联系运营平台申请')
}

// 显示二维码图片
function showQrImgFunc(recordId){
  $qrcShellViewByQrc(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}


// 显示绑定管理
function showBind(recordId){
  bindRef.value.show(recordId)
}


function  updateState (recordId, state) { // 【更新状态】

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return $infoBox.confirmDangerPromise(title, '').then(() => {
    return reqLoad.updateById(API_URL_MCH_QR_CODE_LIST, recordId, { qrcState: state })
  })

}

 // 解绑设备
  function unBindFunc(recordId) {
    const title = '确认解绑？'
    const content = '解绑后商户将无法使用该码牌！'
    $infoBox.confirmDanger(title, content, () => {
      return $unbindQrc(recordId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('解绑成功')
      })
    })
  }

  // 受支持的设备
  function getBindDeviceFunc(recordId) {
    jeepayQrcDeviceListRef.value.show(recordId)
  }


// function batchChecked(checked){
//   vdata.listRecords.forEach(element => {
//     element.checked = checked
//   })
// }

function infoTableSelectChangeFunc(selectedRowKeys){

  // 获取真实的qrcId 
  let qrcIdList : any = []
  selectedRowKeys.forEach(el => qrcIdList.push(el) )

  // 遍历 vdata.listRecords 如果selectedRowKeys数组中存在对应的id,则将其checked改为true,反之false
  vdata.listRecords.forEach(element => {
    qrcIdList.includes(element.qrcId) ? element.checked = true : element.checked = false
  })
}

// 第一次点击导出的事件（ 筛选条件的导出 ）
function tableExportFunc(){
  vdata.exportVisible = true
  vdata.exportModel = 'infoAndUrl' //默认excel

  vdata.listExportIds = null //批量选择清空 
}


// 第一次点击导出的事件（ 批量选择的导出 ）
function tableExportByBatchSelectFunc(){

  vdata.listExportIds = []
  vdata.listRecords.forEach(element => {
    if(element.checked){
      vdata.listExportIds.push(element.qrcId)
    }
  })

  if(vdata.listExportIds.length <= 0){
    return $infoBox.message.error('请选择数据')
  }

  vdata.exportVisible = true
  vdata.exportModel = 'infoAndUrl' //默认excel
}


// 弹层点击确认按钮的事件
function tableExportDowonloadFunc(){

  vdata.exportVisible = false

  let queryCond :any = { 'exportModel': vdata.exportModel, 'pageSize': -1 } //搜索条件
  
  if(typeof vdata.listExportIds == 'object' && vdata.listExportIds != null){
    queryCond.idsStr = ''
    vdata.listExportIds.forEach(r => {
        queryCond.idsStr += (r + '_')
    })
    queryCond.idsStr = queryCond.idsStr.substring(0, queryCond.idsStr.length - 1)

  }else{
    queryCond = Object.assign(queryCond, vdata.searchData)
  }

  return $exportExcel(exportExcelUrl.qrCodes, queryCond).then(res => {
         
         if(vdata.exportModel == 'infoAndUrl'){
           fileDownload(res.data, '码牌信息导出_'+ getCurrentDatetime() +'.xlsx')
         }else{
           fileDownload(res.data, '码牌图片导出_'+ getCurrentDatetime() +'.zip')
         }

      }).catch ((error) =>{console.log(error)} )

}

  // 按批次号划拨
  function allotByBatchIdFunc() {
    vdata.allotObject.allotType = 'batch'
    vdata.allotObject.batchId = ''
    vdata.allotByBatchIdVisible = true
  }
  
  // 按批次号划拨，批次号输入完成
  function allotOk() {
    allotFormModel.value.validate().then((valid: any) =>{
      vdata.allotByBatchIdVisible = false
      jeepayModelAgentList.value.show()
    })
  }

  // 勾选划拨设备
  function allotBatchFunc() {

    vdata.listExportIds = []
    vdata.listRecords.forEach(element => {
      if(element.checked){
        vdata.listExportIds.push(element.qrcId)
      }
    })

    if(vdata.listExportIds.length <= 0){
      return $infoBox.message.error('请选择数据')
    }

    vdata.allotObject.allotType = 'select'
    jeepayModelAgentList.value.show()
  }

  // 划拨单个设备
  function allotFunc(record) {
    vdata.allotObject.allotType = 'select'
    vdata.listExportIds = []
    vdata.listExportIds.push(record.qrcId)

    jeepayModelAgentList.value.show()
  }

  // 划拨/收回选择完成
  function searchAgentFinishFunc(selectObject) {

    vdata.allotObject.agentNo = selectObject[0]
    vdata.allotObject.allotOrRecover = selectObject[1]
    
    if (vdata.allotObject.allotOrRecover == 'allot' && !vdata.allotObject.agentNo) {
      $infoBox.message.error('请选择代理商')
      return
    }

    if (vdata.listExportIds.length > 0) {
      vdata.allotObject.allotIds = vdata.listExportIds.join(',')
    }

    $allotQrc(vdata.allotObject).then(res => {
      vdata.listExportIds = [] // 清空多选
      $infoBox.message.success('保存成功')
      jeepayModelAgentList.value.close()
      searchFunc()
    })
  }

  function onReset(){
      //重置搜索内容
      dateRangePicker.value.returnSelectModel()
      vdata.searchData = { queryDateRange: '' }
    }
</script>
